<?php

namespace App\Models\Admin;

use App\Models\BaseModel;
use App\Common\ValidateHandler;
use App\Common\AliossHandler;
use Auth;

class Banner extends BaseModel
{
    protected $fillable = [
        'id', 'store_id', 'cover', 'url',
        'type', 'status', 'sort',
        'created_at', 'updated_at'
    ];

    public function getList($pageSize)
    {
        $storeId = Auth::guard('admin')->user()->store_id;
        if ($storeId == 0) {
            // 管理员查看全部店铺轮播
            $data = $this->orderBy('store_id')->orderBy('sort', 'desc')->paginate($pageSize)->toArray();
        } else {
            // 店家只能查看自己店的轮播
            $data = $this->where('store_id', $storeId)->orderBy('store_id')->orderBy('sort', 'desc')->paginate($pageSize)->toArray();
        }
        $data = $this->handleData($data);

        return $this->success($data);
    }

    private function handleData($data)
    {
        foreach ($data['data'] as $k => $banner) {
            $data['data'][$k]['cover'] = AliossHandler::read('banner', $banner['cover']);
            $data['data'][$k]['origin'] = $banner['cover'];
        }

        return $data;
    }

    public function handle($data)
    {
        $arr = [];
        $id = $data['id'];

        $arr['url'] = $data['url'];
        $arr['cover'] = $data['cover'];
        $arr['status'] = $data['status'];
        $arr['type'] = $data['type'];
        $arr['sort'] = empty($data['sort']) ? 0 : $data['sort'];

        $userStoreId = Auth::guard('admin')->user()->store_id; //用户店铺id 0为管理员
        if ($userStoreId == 0) {
            // 管理员提交
            $arr['store_id'] = empty($data['store_id']) ? 0 : $data['store_id'];
            if ($arr['store_id'] == 0) return $this->error(['info' => '请选择店铺']);
        } else {
            $arr['store_id'] = $userStoreId;
        }

        $result = $this->validateData($arr);
        if (!$result['res'])
            return $this->error($result);

        if ($id == 'new') {
            $this->create($arr);
        } else {
            $this->where('id', $id)->update($arr);
        }

        return $this->success(['info' => '操作成功']);
    }

    private function validateData($data)
    {
        $arr = [
            0 => [
                'name' => '轮播链接',
                'value' => $data['url'],
                'func' => 'is_empty'
            ],
            1 => [
                'name' => '轮播封面',
                'value' => $data['cover'],
                'func' => 'is_empty'
            ],
            2 => [
                'name' => '轮播类型',
                'value' => $data['type'],
                'func' => 'is_empty'
            ]
        ];

        return ValidateHandler::do($arr);
    }

    public function deleteBanner($data)
    {
        $id = $data['id'];
        $this->where('id', $id)->delete();

        return $this->success(['info' => '删除成功']);
    }
}
